import "./index.scss";
import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Space,
  Modal,
  Radio,
  Upload,
  message,
  Checkbox,
  DatePicker,
  // RangePicker,
} from "antd";
import { ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import axios from "../../../../../utils/http.jsx";
import PageName from "../../../../../components/PageName/index.jsx";
import { useLocation } from "react-router-dom";
// 日期格式转换
import { parseTime } from "@/utils/date.jsx";
// , onCancel
// 日期选择器
const { RangePicker } = DatePicker;
//和上传有关的想法
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};
const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
  const [addForm] = Form.useForm();
  const addOpen = () => {
    onCancel();
    addForm.resetFields();
    setImageUrl();
  };
  ///////////以下都是头像相关的
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleChange = (info) => {
    //判断他的类型和大小
    const isJpgOrPng =
      info.file.type === "image/jpeg" ||
      info.file.type === "image/png" ||
      info.file.type === "image/jpg";
    if (!isJpgOrPng) {
      return message.error("只能上传 jpeg/jpg/png 图片");
    }
    const isLt2M = info.file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      return message.error("最大只能上传2M的图片");
    }
    //将文件对象转成base64的地址，img才能显示出来
    getBase64(info.file.originFileObj, (url) => {
      setImageUrl(url);
    });
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  const customRequest = () => {};

  return (
    <Modal
      forceRender
      open={open}
      title="添加焦点图"
      okText="确定"
      cancelText="取消"
      onCancel={addOpen}
      onOk={() => {
        addForm
          .validateFields()
          .then((values) => {
            addForm.resetFields();
            onCreate(values);
            setImageUrl();
          })
          .catch((info) => {});
      }}
    >
      <Form form={addForm} name="form_in_modal" colon={false}>
        <Form.Item
          label="图片"
          name="myfile"
          rules={[{ required: true, message: "请选择图片" }]}
        >
          <Upload
            fileList={fileList}
            name="avatar"
            listType="picture-card"
            showUploadList={false}
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            onChange={handleChange}
            customRequest={customRequest}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: "100%",
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          name="title"
          label="图片标题"
          rules={[
            {
              required: true,
              message: "请输入标题！",
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="有效时间"
          name="date"
          rules={[
            {
              required: true,
              message: "请输入投放时间！",
            },
          ]}
        >
          {/* <RangePicker /> */}
          <Input />
        </Form.Item>
        <Form.Item
          label="选择状态"
          style={{ width: "250px" }}
          name="status"
          rules={[
            {
              required: true,
              message: "请选择状态！",
            },
          ]}
        >
          {/* defaultValue="全部" */}
          <Radio.Group>
            <Radio value="展示中">展示中</Radio>
            <Radio value="未展示">未展示</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};
const CollectionCreateForm1 = ({
  editOpen,
  onCreate1,
  onCancel1,
  editInitial,
}) => {
  // 上传
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleChange = (info) => {
    //判断他的类型和大小
    const isJpgOrPng =
      info.file.type === "image/jpeg" ||
      info.file.type === "image/png" ||
      info.file.type === "image/jpg";
    if (!isJpgOrPng) {
      return message.error("只能上传 jpeg/jpg/png 图片");
    }
    const isLt2M = info.file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      return message.error("最大只能上传2M的图片");
    }
    //将文件对象转成base64的地址，img才能显示出来
    getBase64(info.file.originFileObj, (url) => {
      setImageUrl(url);
    });
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  const [editForm] = Form.useForm();
  useEffect(() => {
    editForm.setFieldsValue(editInitial);
    setImageUrl("/api" + editInitial.image);
  }, [editInitial]);
  return (
    <Modal
      forceRender
      open={editOpen}
      title="编辑焦点图"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel1}
      onOk={() => {
        editForm
          .validateFields()
          .then((values) => {
            editForm.resetFields();
            onCreate1(values);
          })
          .catch((info) => {});
      }}
    >
      <Form form={editForm} name="form_in_modal" colon={false}>
        <Form.Item
          label="图片"
          name="image"
          // rules={[{ required: true, message: "请选择图片" }]}
        >
          <Upload
            fileList={fileList}
            name="avatar"
            listType="picture-card"
            showUploadList={false}
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            onChange={handleChange}
            // customRequest={customRequest}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: "100%",
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          name="title"
          label="图片标题"
          // rules={[
          //   {
          //     required: true,
          //     message: "请输入标题！",
          //   },
          // ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="投放时间"
          name="effective_data"
          // rules={[
          //   {
          //     required: true,
          //     message: "请输入投放时间！",
          //   },
          // ]}
        >
          {/* <RangePicker /> */}
          <Input />
        </Form.Item>
        <Form.Item
          label="选择状态"
          style={{ width: "250px" }}
          name="status"
          // rules={[
          //   {
          //     required: true,
          //     message: "请选择状态！",
          //   },
          // ]}
        >
          {/* defaultValue="全部" */}
          <Radio.Group>
            <Radio value="展示中">展示中</Radio>
            <Radio value="未展示">未展示</Radio>
          </Radio.Group>
        </Form.Item>
        {/* <Form.Item label="投放城市" name="city" valuePropName="checked">
          <Checkbox.Group options={options} />
        </Form.Item> */}
      </Form>
    </Modal>
  );
};
const ViewFocus = () => {
  // 时间转换
  const date = () => {};
  // 消息提示
  const [messageApi, contextHolder] = message.useMessage();
  const success = () => {
    messageApi.open({
      type: "success",
      content: "添加成功！",
    });
  };
  // 删除模态框
  const { confirm } = Modal;
  // 获取全部数据
  useEffect(() => {
    getFocus();
  }, []);
  // 获取从上个页面传递过来的数据
  const state = useLocation();
  //获取焦点图数据
  const getFocus = () => {
    axios({
      url: "/focus/getFocusDetails",
      method: "post",
      data: {
        type: state.state.position,
      },
    })
      .then((res) => {
        setDataList(res.data);
      })
      .catch((err) => {});
  };
  // 搜索数据
  const [form] = Form.useForm();
  const [createFrom] = Form.useForm();

  // 搜索方法
  const searchBtn = (params) => {
    if (params.status == undefined) {
      params.status = "";
    }
    if (params.keywords == undefined) {
      params.keywords = "";
    }
    axios({
      url: "/focus/getSingleFocusDetails",
      method: "get",
      params: {
        status: params.status,
        title: params.keywords,
        type: "首页",
      },
    })
      .then((res) => {
        setDataList(res.data);
      })
      .catch((err) => {});
  };
  // 清空
  const onClear = () => {
    form.resetFields();
    getFocus();
  };
  // 表格数据
  const [dataList, setDataList] = useState([]);
  // 表格列
  const columns = [
    // {
    //   title: "编号", //表格列名
    //   dataIndex: "f_id", //该列对应数据字段
    //   key: "f_id", //该列唯一值
    //   align: "center",
    // },
    {
      title: "序号",
      dataIndex: "index",
      align: "center",
      // render: (text, record, index) => `${index + 1}`,
      render: (text, record, index) => index + (currentPage - 1) * 5 + 1,
    },
    {
      title: "位置", //表格列名
      dataIndex: "position", //该列对应数据字段
      key: "position", //该列唯一值
      align: "center",
    },
    {
      title: "图片",
      dataIndex: "img",
      key: "img",
      render: (_, record) => (
        <Space size="middle">
          <img className="img" src={"/api" + record.img} alt="" />
        </Space>
      ),
      align: "center",
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      align: "center",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      align: "center",
    },
    {
      title: "有效期",
      dataIndex: "effective_data",
      key: "effective_data",
      align: "center",
    },
    {
      title: "发布者",
      dataIndex: "publisher",
      key: "publisher",
      align: "center",
    },
    {
      title: "发布时间",
      dataIndex: "publish_date",
      key: "publish_date",
      align: "center",
      render: (_, { publish_date }) => {
        return parseTime(publish_date, "{y}-{m}-{d} {h}:{i}:{s}");
      },
    },
    {
      title: "操作",
      align: "center",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              editFrom(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              deleteFrom(record);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];
  // 添加
  const [open, setOpen] = useState(false);
  const onCreate = (values) => {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDay();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month < 10) {
      month = "0" + month;
    }
    if (day < 10) {
      day = "0" + day;
    }
    var sqlTime =
      year +
      "-" +
      month +
      "-" +
      day +
      " " +
      hours +
      ":" +
      minutes +
      ":" +
      seconds;
    //第一步，得到一个formData盒子
    let myFormData = new FormData();
    //第二步，讲文件装到这个盒子里面去  组装数据
    // myFormData.append(内容的名字，内容)  如果这个内容是一个文件，放的就是文件对象
    myFormData.append("position", state.state.position);
    myFormData.append("image", values.myfile.file.originFileObj);
    myFormData.append("title", values.title);
    myFormData.append("status", values.status);
    myFormData.append("effectiveDate", values.date);
    myFormData.append("publisher", "admin");
    myFormData.append("date", sqlTime);
    axios({
      url: "/focus/addFocus",
      method: "post",
      data: myFormData,
    })
      .then((res) => {
        if (res.code == 200) {
          success();
          setOpen(false);
          getFocus();
        }
      })
      .catch((err) => {});
  };
  // 添加弹框关闭
  const onCancel = () => {
    setOpen(false);
  };
  // 编辑
  const [editInitial, setEditInitial] = useState({});
  const [editOpen, setEditOpen] = useState(false);
  const [editId, setEditId] = useState();
  const editFrom = (record) => {
    let initialData = {
      image: record.img,
      title: record.title,
      effective_data: record.effective_data,
      status: record.status,
    };
    setEditInitial(initialData);
    setEditId(record.f_id);
    setEditOpen(true);
  };
  // 确认编辑
  const onCreate1 = (values) => {
    let myFormData = new FormData();
    myFormData.append("id", editId);
    myFormData.append("image", values.image.file.originFileObj);
    myFormData.append("title", values.title);
    myFormData.append("effectiveDate", values.effective_data);
    myFormData.append("status", values.status);
    axios({
      url: "/focus/updateFocus",
      method: "post",
      data: myFormData,
    })
      .then((res) => {
        if (res.code == 200) {
          messageApi.open({
            type: "success",
            content: "修改成功！",
          });
          setEditOpen(false);
          getFocus();
        } else {
          messageApi.open({
            type: "error",
            content: "修改失败！",
          });
          setEditOpen(false);
        }
      })
      .catch((err) => {});
  };
  //删除
  const deleteFrom = (record) => {
    confirm({
      title: "你确定要删除吗?",
      icon: <ExclamationCircleFilled />,
      okText: "Yes",
      okType: "danger",
      cancelText: "No",
      onOk() {
        axios({
          url: "/focus/delFocus",
          method: "post",
          data: {
            f_id: record.f_id,
          },
        })
          .then((res) => {
            if (res.code == 200) {
              messageApi.open({
                type: "success",
                content: "删除成功！",
              });
              getFocus();
            }
          })
          .catch((err) => {});
      },
      onCancel() {},
    });
  };
  // 分页
  // 页数
  const [currentPage, setCurrentPage] = useState(1);
  // 页面改变
  const onChange = (page) => {
    setCurrentPage(page.current);
  };
  return (
    <div>
      {contextHolder}
      {/* <div className="RedPacket">
        <div className="RedPacketDiv">焦点图详情</div>
      </div> */}
      <PageName name="焦点图详情"></PageName>
      {/* 搜索栏 */}
      <div className="RedPacketFrom">
        <Form
          form={form}
          name="horizontal_login"
          layout="inline"
          onFinish={searchBtn}
        >
          <Form.Item label="状态" style={{ width: "200px" }} name="status">
            {/* defaultValue="全部" */}
            <Select placeholder="请选择">
              {/* <Select.Option value="全部">全部</Select.Option> */}
              <Select.Option value="展示中">展示中</Select.Option>
              <Select.Option value="未展示">未展示</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="keywords" label="标题">
            <Input placeholder="请输入关键词查询" />
          </Form.Item>
          <Form.Item shouldUpdate>
            {() => (
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            )}
          </Form.Item>
          <Form.Item>
            <Button onClick={onClear}>清空</Button>
          </Form.Item>
        </Form>
      </div>
      {/* 添加 */}
      <div className="RedPacketBtn">
        <Button
          type="primary"
          onClick={() => {
            setOpen(true);
          }}
        >
          添加
        </Button>
      </div>
      {/* 表格 */}
      <div>
        <Table
          className="RedPacketTable"
          columns={columns}
          pagination={{
            defaultCurrent: 1,
            total: dataList.length,
            defaultPageSize: 5,
            // 只有一页的时候是否隐藏
            hideOnSinglePage: true,
          }}
          dataSource={dataList}
          rowKey={(record) => record.f_id}
          current={currentPage}
          onChange={onChange}
        />
      </div>
      {/* 新增弹框 */}
      <div>
        <CollectionCreateForm
          open={open}
          onCreate={onCreate}
          onCancel={onCancel}
        />
      </div>
      {/* 编辑 */}
      <div>
        <CollectionCreateForm1
          editOpen={editOpen}
          onCreate1={onCreate1}
          onCancel1={() => {
            setEditOpen(false);
          }}
          editInitial={editInitial}
        />
      </div>
    </div>
  );
};

export default ViewFocus;
